package com.huawei.csi.tool.ui;

import com.huawei.csi.tool.event.AnimFinishedEvent;
import com.huawei.csi.tool.event.EventBusUtil;
import javafx.animation.*;
import javafx.scene.Node;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.scene.shape.Circle;
import javafx.scene.shape.SVGPath;
import javafx.util.Duration;

/**
 * 初始化加载动画
 *
 * @author lxw
 */
public class InitialLoadingPane extends Pane {

    public InitialLoadingPane() {
        init();
    }

    @SuppressWarnings("all")
    private void init() {
        int w = 650;
        int h = 516;
        int radius = 64; // 半经
        EventBusUtil.getEventBus().register(this);
        setPrefSize(w, h); // 设置宽高
        SVGPath icon = new SVGPath(); // svg图标
        icon.setScaleX(2);
        icon.setScaleY(2);
        icon.setContent("M19.6,7.4v-.4l7.9-2.5,2.1.3v22.6l-2.2.3-7.8-2.5v-.4l3.9-.5V7.9l-3.9-.5ZM21.1,4.2v-.5L2.3,1.4v29.4l18.8-2.3v-.4l-7.7-2.5-4.8.5V6l4.9.6,7.6-2.4Z");
        icon.setFill(new LinearGradient(
                0.0, 0.0, 1.0, 0.0, true, CycleMethod.REPEAT,
                new Stop(0.0, new Color(0.11, 0.52, 0.93, 1.0)),
                new Stop(1.0, new Color(0.68, 0.05, 0.93, 1.0))));
        StackPane iconPane = new StackPane(icon);
        iconPane.setPrefSize(radius, radius);
        iconPane.setStyle("-fx-background-color: " + ("#2b2b2b") + ";-fx-background-radius: " + radius / 2.0 + "px");
        iconPane.setEffect(new DropShadow());
        iconPane.setLayoutX((w - radius) / 2.7);
        iconPane.setLayoutY((h - radius) / 2.0);
        getChildren().add(iconPane);
        iconPane.setOpacity(0.2);
        Circle circle = new Circle(70); // 创建圆
        FadeTransition fadeTransition = new FadeTransition(Duration.seconds(1.5), iconPane); // 淡入淡出的事件
        fadeTransition.setFromValue(0.2);
        fadeTransition.setToValue(1.0);
        PathTransition pathTransition = new PathTransition(Duration.seconds(2), circle, iconPane); // 路径转换
        ScaleTransition scaleTransition = scaleTransition(iconPane); // 比例转换
        SequentialTransition animation = new SequentialTransition(fadeTransition, pathTransition, scaleTransition); // 顺序过渡
        animation.setInterpolator(Interpolator.EASE_IN); // 动画开始缓慢，然后平稳加速。
        animation.setOnFinished(event -> {
            EventBusUtil.getEventBus().post(new AnimFinishedEvent());
        });
        animation.play();
    }

    private ScaleTransition scaleTransition(Node node) {
        ScaleTransition scaleTransition = new ScaleTransition(Duration.seconds(1.2), node);
        scaleTransition.setByX(2);
        scaleTransition.setByY(2);
        return scaleTransition;
    }

}
